
import React, { useCallback, useEffect, useState } from 'react'
import InfiniteScroll from 'react-infinite-scroll-component';
import Post from "./Post"
import { httpgetPostList } from '../../apis';
import { List, message, Avatar, Skeleton, Divider } from 'antd';

import "./PostList.scss"

const LEN = 10;

export default function PostList(props) {
  const list = props.state.list;
  const totNum = props.state.totNum;
  const dispatch = props.dispatch;
  const getList = useCallback(async (start,len)=>{
    let data = {};
    data.start = start;
    data.len = len;
    let res = await httpgetPostList(data);
    return res;
  },[]);
  useEffect(()=>{
    (async()=>{
      let res = await getList(0,10);
      dispatch({
        type: "initList",
        list: res.list
      });
      dispatch({
        type: "setTotNum",
        totNum: res.totNum
      });
    })()
  },[]);
  const loadMoreData = async () => {
    console.log("loadData");
    console.log(list);
    let res = await getList(list.length,LEN);
    console.log(res);
    dispatch({
      type: "addList",
      list: res.list
    });
    dispatch({
      type: "setTotNum",
      totNum: res.totNum
    });
  }
  return (
    <div className='PostList-container'>
      <InfiniteScroll
        dataLength={list.length}
        next={loadMoreData}
        hasMore={list.length < totNum}
        loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
        endMessage={<Divider plain>It is all, nothing more 🤐</Divider>}
        scrollableTarget="scrollableDiv"
      >
      {
        list.map(post=>(
          <Post post={post} key={post.postId}></Post>
        ))
      }
      </InfiniteScroll>
    </div>
  )
}
